package com.taptech.doufu.util;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import com.taptech.doufu.R;

import java.util.List;

/**
 * Created by longsiyang on 15/12/1.
 */
public class ActivityUtil
{

    private static String AUTHORITY = null;

    public static void getShortcutToDesktopIntent(Context context)
    {
        if(isShortCutExist(context, context.getString(R.string.app_name))){
            return;
        }
        if(hasInstallShortcut(context)){
            return;
        }
        if (isExistInSharedPreference(context))
        {
            return;
        }
        deleteShortCut(context);
        Intent intent = new Intent();
        intent.setClass(context, context.getClass());
        /*以下两句是为了在卸载应用的时候同时删除桌面快捷方式*/
        intent.setAction("android.intent.action.MAIN");
        intent.addCategory("android.intent.category.LAUNCHER");
        Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
        // 不允许重建
        shortcut.putExtra("duplicate", false);
        // 设置名字
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, context.getString(R.string.app_name));
        // 设置图标
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(context, R.drawable.new_icon));
        // 设置意图和快捷方式关联程序
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
        context.sendBroadcast(shortcut);
        saveInfoInSharedPreference(context);
    }

    /**
     * 判断是否已添加快捷方式：
     * 暂时没有方法能够准确的判断到快捷方式，原因是，
     * 1、不同厂商的机型他的快捷方式uri不同，我遇到过HTC的他的URI是content://com.htc.launcher.settings/favorites?notify=true
     * 2、桌面不只是android自带的，可能是第三方的桌面，他们的快捷方式uri都不同
     * <p/>
     * 提供一个解决办法，创建快捷方式的时候保存到preference，或者建个文件在SD卡上，下次加载的时候判断不存在就先发删除广播，再重新创建
     * <p/>
     * 添加权限:<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" ></uses-permission>
     */
    public static boolean hasInstallShortcut(Context context)
    {
        boolean hasInstall = false;

        String AUTHORITY = "com.android.launcher.settings";
        int systemversion = Build.VERSION.SDK_INT;
        // Log.i("Build.VERSION.SDK==========>", systemversion + "");
         /*大于8的时候在com.android.launcher2.settings 里查询（未测试）*/
        if (systemversion >= 8)
        {
            AUTHORITY = "com.android.launcher2.settings";
        }
        Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/favorites?notify=true");

        Cursor cursor = context.getContentResolver().query(CONTENT_URI, new String[]{"title"}, "title=?", new String[]{context.getString(R.string.app_name)}, null);

        if (cursor != null && cursor.getCount() > 0)
        {
            hasInstall = true;
        }

        return hasInstall;
    }

    /**
     * 删除快捷方式
     */
    public static void deleteShortCut(Context context)
    {
        Intent shortcut = new Intent("com.android.launcher.action.UNINSTALL_SHORTCUT");
        //快捷方式的名称
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, context.getString(R.string.app_name));
        /**删除和创建需要对应才能找到快捷方式并成功删除**/
        Intent intent = new Intent();
        intent.setClass(context, context.getClass());
        intent.setAction("android.intent.action.MAIN");
        intent.addCategory("android.intent.category.LAUNCHER");
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
        context.sendBroadcast(shortcut);
    }

    public static boolean isExistInSharedPreference(Context context)
    {
        SharedPreferences mySharedPreferences = context.getSharedPreferences("desktop_show", Activity.MODE_PRIVATE);
        return mySharedPreferences.getBoolean("is_exist", false);
    }

    public static void saveInfoInSharedPreference(Context context)
    {
        SharedPreferences mySharedPreferences = context.getSharedPreferences("desktop_show", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = mySharedPreferences.edit();
        editor.putBoolean("is_exist", true);
        editor.commit();
    }

    public static boolean isShortCutExist(Context context, String title) {

        boolean isInstallShortcut = false;

        if (null == context || TextUtils.isEmpty(title))
            return isInstallShortcut;

        if (TextUtils.isEmpty(AUTHORITY))
            AUTHORITY = getAuthorityFromPermission(context);

        final ContentResolver cr = context.getContentResolver();

        if (!TextUtils.isEmpty(AUTHORITY)) {
            try {
                final Uri CONTENT_URI = Uri.parse(AUTHORITY);

                Cursor c = cr.query(CONTENT_URI, new String[] { "title",
                                "iconResource" }, "title=?", new String[] { title },
                        null);

                // XXX表示应用名称。
                if (c != null && c.getCount() > 0) {
                    isInstallShortcut = true;
                }
                if (null != c && !c.isClosed())
                    c.close();
            } catch (Exception e) {
                Log.e("isShortCutExist", e.getMessage());
            }

        }
        return isInstallShortcut;
    }

    public static String getAuthorityFromPermissionDefault(Context context) {
        return getThirdAuthorityFromPermission(context, "com.android.launcher.permission.READ_SETTINGS");
    }

    public static String getAuthorityFromPermission(Context context) {
        // 获取默认
        String authority = getAuthorityFromPermissionDefault(context);
        // 获取特殊第三方
        if (authority == null || authority.trim().equals("")) {
            String packageName = getCurrentLauncherPackageName(context);
            packageName += ".permission.READ_SETTINGS";
            authority = getThirdAuthorityFromPermission(context, packageName);
        }
        // 还是获取不到，直接写死
        if (TextUtils.isEmpty(authority)) {
            int sdkInt = android.os.Build.VERSION.SDK_INT;
            if (sdkInt < 8) { // Android 2.1.x(API 7)以及以下的
                authority = "com.android.launcher.settings";
            } else if (sdkInt < 19) {// Android 4.4以下
                authority = "com.android.launcher2.settings";
            } else {// 4.4以及以上
                authority = "com.android.launcher3.settings";
            }
        }
        authority = "content://" + authority + "/favorites?notify=true";
        return authority;
    }

    public static String getCurrentLauncherPackageName(Context context) {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        ResolveInfo res = context.getPackageManager()
                .resolveActivity(intent, 0);
        if (res == null || res.activityInfo == null) {
            // should not happen. A home is always installed, isn't it?
            return "";
        }
        if (res.activityInfo.packageName.equals("android")) {
            return "";
        } else {
            return res.activityInfo.packageName;
        }
    }

    public static String getThirdAuthorityFromPermission(Context context,
                                                         String permission) {
        if (TextUtils.isEmpty(permission)) {
            return "";
        }

//        try {
//            List<PackageInfo> packs = context.getPackageManager()
//                    .getInstalledPackages(PackageManager.GET_PROVIDERS);
//            if (packs == null) {
//                return "";
//            }
//            for (PackageInfo pack : packs) {
//                ProviderInfo[] providers = pack.providers;
//                if (providers != null) {
//                    for (ProviderInfo provider : providers) {
//                        if (permission.equals(provider.readPermission)
//                                || permission.equals(provider.writePermission)) {
//                            if (!TextUtils.isEmpty(provider.authority)// 精准匹配launcher.settings，再一次验证
//                                    && (provider.authority)
//                                    .contains(".launcher.settings"))
//                                return provider.authority;
//                        }
//                    }
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        return "";
    }
}
